package communication;

import lombok.Data;

@Data
public class Customer implements Runnable {
    final Clerk clerk;

    @Override
    public void run() {
        int inputNum;
        while (true) {
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            synchronized (clerk) {
                if (clerk.getProduction() == 0) {
                    try {
                        clerk.wait();
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                } else {
                    inputNum = (int) (Math.random() * 10 + 1);
                    if (inputNum > clerk.getProduction()) {
                        System.out.println("产品余量不足，请等待...");
                        while (inputNum > clerk.getProduction())
                            try {
                                clerk.wait();
                            } catch (InterruptedException e) {
                                throw new RuntimeException(e);
                            }
                        System.out.println(Thread.currentThread().getName() + "--> 成功购买 " + inputNum + " 件产品。");
                        clerk.setProduction(clerk.getProduction() - inputNum);
                    } else {
                        System.out.println(Thread.currentThread().getName() + "--> 成功购买 " + inputNum + " 件产品。");
                        clerk.setProduction(clerk.getProduction() - inputNum);
                    }
                }
            }
        }
    }

    public Customer(Clerk clerk) {
        this.clerk = clerk;
    }
}
